package com.fjsaas.quartz;

import java.text.ParseException;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import com.fjsaas.web.constants.Constants;
import com.fjsaas.web.utils.MyUtil;

public class QuartzTaskService {

	@Autowired
	private SchedulerFactoryBean schedulerFactoryBean;
	@Autowired
	private ApplicationContext context;

	public void runTask(TaskDetail taskDetail) throws SchedulerException, ParseException {
		Scheduler scheduler = schedulerFactoryBean.getScheduler();
		JobKey jobKey = new JobKey(taskDetail.getJobName(), taskDetail.getJobGroup());
		taskDetail.getMap().put(Constants.APPLICATION_CONTEXT, context);
		JobDataMap jobDataMap = new JobDataMap();
		jobDataMap.put(Constants.JOB_KEY, taskDetail);
		if(!scheduler.checkExists(jobKey)){
			JobDetail jobDetail = JobBuilder.newJob(taskDetail.getJob()).withIdentity(jobKey)
					.storeDurably().build();
			//jobDetail.getJobDataMap().put(Constants.JOB_KEY, taskDetail);
			scheduler.addJob(jobDetail, true);
		}
		
		
		
		//storeDurably 默认为false，在scheduler中不允许job单独存在（不绑定trigger
		Trigger trigger = null;
		TriggerKey triggerKey = new TriggerKey(MyUtil.getUUID(),taskDetail.getJobGroup());
		if (taskDetail.getCronExpression() != null) {
			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(taskDetail.getCronExpression());
			trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey)
					.withSchedule(scheduleBuilder).forJob(jobKey).usingJobData(jobDataMap).build();
		} else {
			trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey)
					.startAt(taskDetail.getStartDate())
					.withSchedule(SimpleScheduleBuilder.simpleSchedule().withRepeatCount(taskDetail.getRepeatCount()).withIntervalInSeconds(taskDetail.getRepeatInterval()))
					.forJob(jobKey)
					.usingJobData(jobDataMap)
					.build();
		}
		scheduler.scheduleJob(trigger);
			
	}
	
}
